<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>医生管理</title>
    <link rel="stylesheet" href="../../../layui/css/layui.css" media="all">
    <link rel="stylesheet" href="../../../layui/layuiAdmin/css/admin.css" media="all">
</head>
<body>

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-form layui-card-header layuiadmin-card-header-auto" style="border-radius: 0;border-top: 4px solid #d2d2d2;">
            <div class="layui-form-item">
               <div style="display: flex">
                   <div class="layui-inline" style="display: flex;flex: 1">
                       <label class="layui-form-label" style="display: flex">医生名</label>
                       <div class="layui-input-inline">
                           <input type="text" name="doctorName" placeholder="请输入医生名" autocomplete="off" class="layui-input">
                       </div>
                   </div>
                   <div class="layui-inline" style="display: flex;flex: 1">
                       <label class="layui-form-label">医生职称</label>
                       <div class="layui-input-inline">
                           <input type="text" name="professional" placeholder="请输入医生职称" autocomplete="off" class="layui-input">
                       </div>
                   </div>
                   <div class="layui-inline" style="display: flex;flex: 1">
                       <label class="layui-form-label">所属医院</label>
                       <div class="layui-input-inline">
                           <select name="hospitalId" id="hospitalSelect" lay-filter="">
                           </select>
                       </div>
                   </div>

               </div>
                <div class="layui-inline" style="display: flex">
                <div class="layui-form-item" >
                    <label class="layui-form-label">账户状态</label>
                    <div class="layui-input-inline">
                        <select name="status" >
                            <option value="">--状态--</option>
                            <option value="0">未开通</option>
                            <option  value="1">已开通</option>
                            <option  value="2">停用</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <button class="layui-btn layuiadmin-btn-useradmin" lay-submit lay-filter="LAY-sysuser-front-search">
                        <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                    </button>
                </div>
                </div>
            </div>
        </div>
        <div class="layui-card-body">

            <div style="padding-bottom: 10px;">
                <button class="layui-btn layuiadmin-btn-useradmin" data-type="batchdel">删除</button>
                <button class="layui-btn layuiadmin-btn-useradmin" data-type="add">添加</button>
            </div>

            <!--  表格数据加载 -->
            <table id="LAY-user-manage" lay-filter="LAY-user-manage"></table>



            <script type="text/html" id="table-useradmin-webuser">
                <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="show"><i class="layui-icon layui-icon-edit"></i>查看</a>
            </script>

            <!--状态判断-->
            <script type="text/html" id="statusTpl">

                {{#  if(d.status == 1){ }}
                <button class="layui-btn layui-btn-xs">已开通</button>
                {{#  } else if(d.status == 2) { }}
                <button class="layui-btn layui-btn-primary layui-btn-xs">停用</button>
                {{#  } else if(d.status == 0) { }}
                <button class="layui-btn layui-btn-danger layui-btn-xs">未开通</button>
                {{#  } }}
            </script>

            <script type="text/html" id="sexTpl">
                {{#  if(d.doctorSex == 1){ }}
                <span>男</span>
                {{#  } else if(d.doctorSex == 2) { }}
                <span>女</span>
                {{#  } }}
            </script>

            <!--  创建时间格式化处理 -->
            <script type="text/html" id="createTimeTpl">
                {{formatDate(d.createTime)}}
            </script>

        </div>
    </div>
</div>

<script src="../../../layui/layui.js"></script>
<script type="text/javascript">
    // 日期格式转换函数
    function formatDate(str) {
        if(str != null){
            var now = new Date(str);
            var year = now.getFullYear();  //取得4位数的年份
            var month = now.getMonth() + 1;  //取得日期中的月份，其中0表示1月，11表示12月
            var date = now.getDate();      //返回日期月份中的天数（1到31）
            var hours = now.getHours();
            var minutes = now.getMinutes();
            var seconds = now.getSeconds();
            return year + "-" + month + "-" + date +" "+hours+":"+minutes+":"+seconds;
        }
        return "";
    }
</script>
<script type="text/javascript">
    layui.use('laydate', function(){
        var laydate = layui.laydate;
        laydate.render({
            elem: '#datetimePicker',
            type: 'datetime'
        });
    });
    layui.config({
        base: '../../../layui/layuiAdmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['layer','table','form'], function(){
        var $ = layui.$
            ,form = layui.form
            ,layer = layui.layer
            ,table = layui.table;

        //加载table
        table.render({
            elem: '#LAY-user-manage'
            ,url:'/sys_doctor/findSysDoctorAll' //后端接口
            ,cellMinWidth: 80 //全局定义常规单元格的最小宽度
            ,title: '部门信息'
            ,cols: [[
                {type: 'checkbox', fixed: 'left'}
                //获得医生数据
                ,{field:'doctorId', title: '医生ID', width:80}
                ,{field:'doctorName', title: '医生姓名', width:100}
                ,{field:'doctorSex', title: '医生性别', width:100,templet: '#sexTpl'}
                ,{field:'doctorPhone', title: '手机号码', width:100}
                ,{field:'hospitalId', title: '所属医院Id', width:100,hide:true}
                ,{field:'hospitalName', title: '所属医院', width:100}
                ,{field:'status', title: '账户状态', width:100,templet: '#statusTpl'}
                ,{field:'createTime', title: '创建时间', width:100}
                ,{field:'avatar', title: '头像', width:100}
                ,{field:'remark', title: '基本信息备注', width:100}
                ,{field:'certificate', title: '资格证', width:100}
                ,{field:'professional', title: '职称', width:100}
                ,{field:'doctorType', title: '医生类型', width:100}
                ,{field:'department', title: '科室', width:100}
                ,{field:'medicalExperience', title: '从医经验', width:100}
                ,{fixed: 'right', title:'操作', toolbar: '#table-useradmin-webuser',width:250}
            ]]
            ,page: {
                curr: 1 //设定初始在第 5 页
                ,limit: 5 //设定初始每页显示 5 条
            },
            limits:[5,10,15,20]
        });

        //监听行工具事件
        table.on('tool(LAY-user-manage)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                layer.confirm('真的删除行么', function(index){
                    $.ajax({
                        url:"http://localhost:8888/sys_doctor/del", //请求后端接口地址
                        type:"post", //请求方式get | post
                        data:{doctorId:data.doctorId}, //提交json字符串对象参数
                        dataType:"json", //后端返回参数类型
                        success:function (res){ //请求成功后回调函数res = JSONObject.toJSONString(resultMap)
                            if(res.code == 0){//成功
                                layer.msg(res.message);//弹出提示
                                table.reload('LAY-user-manage'); //数据刷新
                                layer.close(index); //关闭弹层
                            }else {
                                layer.msg(res.message,{icon: 5});//弹出提示
                            }
                        }
                    })
                });
            } else if(obj.event === 'edit'){
                localStorage.setItem('doctorId', data.doctorId);
                layer.open({
                    type: 2
                    ,title: '修改医生信息'
                    ,skin: 'layui-layer-molv'
                    ,content: 'edit.html'
                    ,maxmin: true
                    ,area: ['480px', '600px']
                    ,btn: ['确定', '取消']
                    // 加载弹出层之前获取选中数据，进行回显
                    ,success: function (layero,index){

                        var body = layer.getChildFrame("body",index);
                        var contentWindow = layero.find('iframe')[0].contentWindow;//得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                        body.find("input[name=doctorId]").val(data.doctorId);
                        body.find("input[name=doctorName]").val(data.doctorName);
                        body.find("input[name=doctorSex][value=1]").attr("checked",data.doctorSex == 1 ? true:false);
                        body.find("input[name=doctorSex][value=2]").attr("checked",data.doctorSex == 2 ? true:false);
                        body.find("input[name=doctorPhone]").val(data.doctorPhone);
                        body.find("input[name=hospitalName]").val(data.hospitalName);
                        body.find("input[name=mobile]").val(data.mobile);
                        body.find("input[name=status][value=0]").attr("checked",data.status == 0 ? true:false);
                        body.find("input[name=status][value=1]").attr("checked",data.status == 1 ? true:false);
                        body.find("input[name=status][value=2]").attr("checked",data.status == 2 ? true:false);
                        body.find("img[id=ID-upload-demo-img]").val(data.avatar)
                        contentWindow.layui.form.render();
                        body.find("input[name=remark]").val(data.remark);
                        body.find("input[name=professional]").val(data.professional);
                        body.find("img[id=ID-upload-demo-img1]").val(data.avatar)
                        body.find("select[id=hospitalSelect]").val(data.hospitalId);
                        body.find("select[name=departmentId][value=1]").val(data.doctorType=1);
                        body.find("select[name=departmentId][value=2]").val(data.doctorType=2);
                        body.find("input[name=department]").val(data.department);
                        body.find("input[name=medicalExperience]").val(data.medicalExperience);
                        contentWindow.layui.form.render("radio");
                        // 重载下来列表
                        contentWindow.layui.form.render("select");
                    }
                    ,yes: function(index, layero){
                        var iframeWindow = window['layui-layer-iframe'+ index]
                            ,submitID = 'LAY-user-front-submit'
                            ,submit = layero.find('iframe').contents().find('#'+ submitID);
                        //监听提交
                        iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
                            var field = data.field; //获取提交的字段
                            console.log(field)
                            $.ajax({
                                url:"http://localhost:8888/sys_doctor/update", //请求后端接口地址
                                type:"post", //请求方式get | post
                                data:JSON.stringify(field), //提交json字符串对象参数
                                contentType:"application/json;charset=utf-8", //发送信息至服务器时内容编码类型
                                dataType:"json", //后端返回参数类型
                                success:function (res){ //请求成功后回调函数res = JSONObject.toJSONString(resultMap)
                                    if(res.code == 0){//成功
                                        layer.msg(res.message);//弹出提示
                                        table.reload('LAY-user-manage'); //数据刷新
                                        layer.close(index); //关闭弹层
                                    }
                                    if(res.code == -1){//系统出问题
                                        layer.msg(res.message,{icon: 5});//弹出提示
                                    }
                                }
                            })
                        });
                        submit.trigger('click');
                    }
                });

            }else if(obj.event === 'show'){
                console.log(data.hospitalId)
                localStorage.setItem('doctorId', data.doctorId);
                localStorage.setItem('doctorSex', data.doctorSex);
                localStorage.setItem('department', data.department);
                localStorage.setItem('professional', data.professional);
                localStorage.setItem('medicalExperience', data.medicalExperience);
                localStorage.setItem('certificate', data.certificate);

                console.log("点击了")
                layer.open({
                    type: 2
                    ,title: '医生信息'
                    ,skin: 'layui-layer-molv'
                    ,content: 'show.html'
                    ,maxmin: true
                    ,area: ['480px', '600px']
                    ,btn: ['返回']
                    // 加载弹出层之前获取选中数据，进行回显
                    ,success: function (layero,index){
                        var body = layer.getChildFrame("body",index);
                        var contentWindow = layero.find('iframe')[0].contentWindow;//得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                        body.find("input[name=doctorId]").val(data.doctorId);
                        body.find("input[name=doctorName]").val(data.doctorName);
                        body.find("input[name=doctorSex]").val(data.doctorSex)
                        body.find("input[name=doctorPhone]").val(data.doctorPhone);
                        body.find("input[name=hospitalName]").val(data.hospitalName);
                        body.find("input[name=mobile]").val(data.mobile);
                        body.find("img[id=certificate").val(data.certificate)
                        contentWindow.layui.form.render();
                        body.find("input[name=remark]").val(data.remark);
                        body.find("input[name=professional]").val(data.professional);
                        body.find("select[id=hospitalSelect]").val(data.hospitalId);
                        body.find("input[name=department]").val(data.department);
                        body.find("input[name=medicalExperience]").val(data.medicalExperience);
                        contentWindow.layui.form.render("radio");
                        // 重载下来列表
                        contentWindow.layui.form.render("select");
                    }
                    ,yes: function(index, layero){
                        layer.close(index); //关闭弹层
                        submit.trigger('click');
                    }
                });

            }
        });


        //监听搜索
        form.on('submit(LAY-sysuser-front-search)', function(data){
            var field = data.field;
            //执行重载
            table.reload('LAY-user-manage', {
                url: 'http://localhost:8888/sys_doctor/search',
                where: field
            });
        });

        //事件
        var active = {
            batchdel: function(){
                var checkStatus = table.checkStatus('LAY-user-manage')
                    ,checkData = checkStatus.data; //得到选中的数据

                if(checkData.length == 0){
                    return layer.msg('请选择数据');
                }

                // 程序走到这里，表示已经有选中要删除的数据了。
                layer.confirm('确定删除吗？',function (){
                    var doctorIds = new Array();
                    $.each(checkData,function (index,item){
                        doctorIds.push(item.doctorId);
                    })
                    // 提交给后端
                    $.ajax({
                        url:"http://localhost:8888/sys_doctor/batchdel",
                        type:"post",
                        data:{ids:doctorIds},
                        traditional:true, // 传统序列化
                        dataType:"json",
                        success:function (res){
                            if(res.code == 0){//成功
                                layer.msg('已删除');
                                table.reload('LAY-user-manage'); //数据刷新
                                layer.close(index); //关闭弹层
                            }else{
                                layer.msg(res.message,{icon: 5});//弹出提示
                            }
                        }
                    })
                })
            }
            , add: function () {
                layer.open({
                    type: 2
                    , title: '添加用户'
                    , skin: 'layui-layer-molv'
                    , content: 'add.html'
                    , maxmin: true
                    , area: ['480px', '650px']
                    , btn: ['确定', '取消']
                    , yes: function (index, layero) {
                        var iframeWindow = window['layui-layer-iframe' + index]
                            , submitID = 'LAY-user-front-submit'
                            , submit = layero.find('iframe').contents().find('#' + submitID);
                        //监听提交--隐藏按钮
                        iframeWindow.layui.form.on('submit(' + submitID + ')', function (data) {
                            var field = data.field; //获取提交的字段
                            // 通过Ajax方式将参数提交到后端--保存数据库中
                            $.ajax({
                                url: "/sys_doctor/save",
                                type: "post",
                                data: JSON.stringify(field),
                                contentType: "application/json;charset=utf-8", //提交参数类型为json格式
                                dataType: "json",
                                success: function (res) {
                                    if (res.code == 0) {//成功
                                        layer.msg(res.message);//弹出提示
                                        table.reload('LAY-user-manage'); //数据刷新
                                        layer.close(index); //关闭弹层
                                    } else {//系统出问题
                                        layer.msg(res.message, {icon: 5});//弹出提示
                                    }
                                }
                            })
                        });
                        submit.trigger('click');
                    }
                });
            }
        };
        // 通过后端动态获取下拉数据
        $.ajax({
            url:"http://localhost:8888/sys_hospital/findSysHospitals",
            type:"get",
            dataType:"json",
            success:function (res){
                // 后端获取部门数据
                var selectData = res.data;
                // 清空列表
                $("#hospitalSelect").empty();
                // 默认的
                $("#hospitalSelect").append(new Option('-请选择所属医院-',''));
                // 循环遍历
                $.each(selectData,function (index,item){
                    $("#hospitalSelect").append(new Option(item.hospitalName,item.hospitalId));
                })
                form.render('select'); // 更新渲染
            }
        })
        $('.layui-btn.layuiadmin-btn-useradmin').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

    });
</script>
</body>
</html>